import React, { Component } from 'react'
import { Carousel, Grid, SearchBar, Flex, WingBlank } from 'antd-mobile'
// import Axios from 'axios'

import { Toast } from 'antd-mobile';

import { getCurrentCity, API, BASE_URL } from '../../utils'

import Nav1 from '../../assets/images/nav-1.png'
import Nav2 from '../../assets/images/nav-2.png'
import Nav3 from '../../assets/images/nav-3.png'
import Nav4 from '../../assets/images/nav-4.png'

import './index.css'
import './index.scss'

const gridsInfo = [
  { icon: Nav1, text: '整租', path: '/home/houselist'},
  { icon: Nav2, text: '合租', path: '/home/houselist'},
  { icon: Nav3, text: '地图找房', path: '/map' },
  { icon: Nav4, text: '去出租', path: '/rent/add' }
]
const grids = gridsInfo.map(_val => ({
  icon: _val.icon,
  text: _val.text,
}));
export default class Index extends Component {
  state = {
    // 轮播图数据
    data: [],
    // 轮播图默认高度
    imgHeight: 176,
    // 租房小组数据
    groups: [],
    // 最新资讯数据
    news:[],
    // 当前定位城市，默认上海
    currentCity: '上海'
  }
  handleMenu(el, index) {
    // el 包含每个菜单的icon和text信息
    // index 点击的菜单项的下标
    // console.log(this.props, el, index);
    this.props.history.push(gridsInfo[index].path)
  }
  async getSwipers() {
    // 发ajax拿轮播图
    try {
      const { data, status } = await API({
        method: 'get',
        url: '/home/swiper'
      })
      if (status !== 200) {
        Toast.fail('Load failed !!!', 1)
        return
      }
      this.setState({
        data: data.body
      })
    } catch (error) {
      console.log(error)
    }
    this.autoFocusInst.focus();
  }
  // 获取租房小组数据
  async getGroups() {
    const res = await API.get(
      '/home/groups?area=AREA%7C88cff55c-aaa4-e2e0'
    )
    this.setState({
      groups: res.data.body
    })
  }
  // 获取最新资讯
  async getNews() {
    const res = await API.get(
      '/home/news?area=AREA%7C88cff55c-aaa4-e2e0'
    )
    this.setState({
      news: res.data.body
    })
  }
  // 渲染最新资讯
  renderNews() {
    return this.state.news.map(item => (
      <div className="news-item" key={item.id}>
        <div className="imgwrap">
          <img
            className="img"
            src={`http://localhost:8080${item.imgSrc}`}
            alt=""
          />
        </div>
        <Flex className="content" direction="column" justify="between">
          <h3 className="title">{item.title}</h3>
          <Flex className="info" justify="between">
            <span>{item.from}</span>
            <span>{item.date}</span>
          </Flex>
        </Flex>
      </div>
    ))
  }
  componentDidMount() {
    this.getSwipers()
    this.getGroups()
    this.getNews()
    const promise = getCurrentCity()
    promise.then(data => {
      const currentCity = data.label
      this.setState({
        currentCity
      })
    })
  }
  render() {
    // console.log(this.state.data.length)
    return (
      <div>
        <div className="search-bar">
          <WingBlank>
            <Flex>
              <Flex.Item className="crrentCity" onClick={() => this.props.history.push('/citylist')}>
                <span>{this.state.currentCity}</span>
                <i className="iconfont icon-arrow"></i>
              </Flex.Item>
              <Flex.Item className="search">
                <SearchBar placeholder="请输入小区地址" ref={searchBar => this.autoFocusInst = searchBar} />
              </Flex.Item>
              <Flex.Item className="map">
                <i className="iconfont icon-map" onClick={() => this.props.history.push('/map')}></i>
              </Flex.Item>
            </Flex>
          </WingBlank>
        </div>
        {
          !this.state.data.length ? null :
            // <WingBlank></WingBlank> 两翼留白，不需要
            // <WingBlank>
            < Carousel
              // 自动切换
              autoplay
              // 是否循环播放
              infinite
            // 切换面板前的回调函数
            // beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
            // 切换面板后的回调函数
            // afterChange={index => console.log('slide to', index)}
            >
              {
                this.state.data.map(item => (
                  <a
                    key={item.id}
                    href="http://www.alipay.com"
                    style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                  >
                    <img
                      src={`${BASE_URL}${item.imgSrc}`}
                      alt=""
                      style={{ width: '100%', verticalAlign: 'top' }}
                      onLoad={() => {
                        // fire window resize event to change height
                        window.dispatchEvent(new Event('resize'));
                        this.setState({ imgHeight: 'auto' });
                      }}
                    />
                  </a>
                ))
              }
            </Carousel >
          // </WingBlank>
        }
        <Grid data={grids} hasLine={false} onClick={this.handleMenu.bind(this)} />
        {/* 租房小组 */}
        <div className="groups">
          <Flex className="groups-title" justify="between">
            <h3>租房小组</h3>
            <span>更多</span>
          </Flex>
          {/*
            data 表示：数据源
            columnNum 表示：列数
            square 表示：是否为正方形
            activeStyle 表示：点击反馈（点击高亮）
            hasLine 表示：是否有边框
            rendeItem 属性：用来 自定义 每一个单元格中的结构
          */}
          <Grid
            data={this.state.groups}
            columnNum={2}
            square={false}
            activeStyle
            hasLine={false}
            renderItem={item => (
              <Flex className="grid-item" justify="between">
                <div className="desc">
                  <h3>{item.title}</h3>
                  <p>{item.desc}</p>
                </div>
                <img src={`${BASE_URL}${item.imgSrc}`} alt="" />
              </Flex>
            )}
          />
        </div>
        {/* 最新资讯： */}
        <div className="news">
          <h3 className="group-title">最新资讯</h3>
          <WingBlank size="md">{this.renderNews()}</WingBlank>
        </div>
      </div> 
    )
  }
}
